Next | Prev | Up | Top | Contents | Index

Hard Links and Symbolic Links

As discussed in the section "Inodes" in this chapter, information about each file, except for the name and directory of the file, is stored in an inode for the file. The name of the file is stored in the file's directory and a link to the file is created by associating the filename with an inode number. This type of link is called a hard link. Although every file is a hard link, the term is usually used only when two or more filenames are associated with the same inode number. Because inode numbers are unique only within a filesystem, hard links cannot be created across filesystem boundaries.

The second and later hard links to a file are created with the ln command, without the -s option. For example, say the current directory contains a file called origfile. To create a hard link called linkfile to the file origfile, give this command:

% ln origfile linkfile 
The output of ls -l for origfile and linkfile shows identical sizes and last modification times:

% ls -l origfile linkfile
-rw-rw-r--    2 joyce    user         4 Apr  5 11:15 origfile
-rw-rw-r--    2 joyce    user         4 Apr  5 11:15 linkfile
Because origfile and linkfile are simply two names for the same file, changes in the contents of the file are visible when using either filename. Removing one of the links has no effect on the other. The file is not removed until there are no links to it (the number of links to the file, the link count, is stored in the file's inode).

Another type of link is the symbolic link. This type of link is actually a file (see Table 3-2). The file contains a text string, which is the pathname of another file or directory. Because a symbolic link is a file, it has its own owners and permissions. The file or directory it points to can be in another filesystem. If the file or directory that a symbolic link points to is removed, it is no longer available and the symbolic link becomes useless until the target is recreated (it is called a dangling symbolic link).

Symbolic links are created with the ln command with the -s option. For example, to create a symbolic link called linkdir to the directory origdir, give this command:

% ln -s origdir linkdir
The output of ls -ld for the symbolic link is shown below. Notice that the permissions and other information don't match. The listing for linkdir shows that it is a symbolic link to origdir.

% ls -ld linkdir origdir
drwxrwxrwt  13 sys     sys  2048 Apr  5 11:37 origdir
lrwxrwxr-x   1 joyce   user    8 Apr  5 11:52 linkdir -> origdir
When you use ".." in pathnames that involve symbolic links, be aware that " .." refers to the parent directory of the true file or directory, not the parent of the directory that contains the symbolic link.

For more information about hard and symbolic links, see the ln(1) reference page and experiment with creating and removing hard and symbolic links.


Next | Prev | Up | Top | Contents | Index